/*Version 1.3
 * Amey Banaye
 * 16 July 2015
 */
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing;
using GTA;
using GTA.Math;
using GTA.Native;
using GTA.NaturalMotion;
using System.Diagnostics;

namespace LOS_SANTOS_AIRLINES
{
    public class Airlines : Script
    {
        Ped player;
        Ped pilot;
        Ped Assistant;
        List<PedHash> PvtPassengers;
        List<Ped> Passengers;
        Vehicle playerCar;
        Vehicle pickUpCar;
        int flightCounter;
        int PvtorPub;
        List<VehicleHash> listPrivatePlanes;
        List<VehicleHash> listAirlinesPlanes;
        List<VehicleHash> listHelicopters;
        bool airplaneBooked;
        bool airplaneEntered;
        bool seatBeltsOn;
        bool readytofly;
        bool airplaneLanding;
        bool flightInProgress;
        bool airplaneSpawned;
        bool takeOffGain;
        bool takeOffInProgress;
        bool supriseActivated;
        bool RappellingOn;
        bool assistantCreated;
        bool flightabort;
        //bool landingactive;
        //bool nearLandingZone;
        bool playerNearAeroplane;
        bool nearResearvationPoint;
        private Vector3 reservationCenter;
        private Vector3 AirlplaneSpawnPoint;
        private List<string> AirportNames;
        private Vector3 flyToAirport;
        private List<Vector3> Airports;
        private List<Vector3> runwayStartPoints;
        private List<Vector3> runwayEndPoints;
        private Vector3 runwayStartPoint;
        private Vector3 runwayEndPoint;
        private float AirplaneSpawnHeading;
        private Vector3 driveTo;
        private Vehicle selectedAirplane;
        bool landingGearsOFF;
        bool customWaypoint;
        bool isHelicopter;
        bool annoncementsOn;
        bool flightSkipped;
        private int _branch;
        private bool _isMenuOpen;
        private Viewport _viewPort;
        private List<GTA.IMenuItem> _menuItems;
        private int _selectedItem;
        VehicleHash selectedPlaneHash;
        Random r = new Random();
        Blip BlipflightStartPoint;
        Blip BlipreservationCentre;
        Blip Checkpoint;
        int flightProgress = 0;
        ProcessStartInfo psi;

        public Airlines()
        {
            player = Game.Player.Character;
            reservationCenter = new Vector3(-1058.879f, -2719.5f, 13.75664f);
            Passengers = new List<Ped>();
            AirlplaneSpawnPoint = new Vector3(-1707.822f, -2866.173f, 13.94445f);
            airplaneSpawned = false;
            flightCounter = 0;

            flightabort = false;
            PvtPassengers = new List<PedHash>();
            PvtPassengers.Add(PedHash.Bankman01);
            PvtPassengers.Add(PedHash.Bankman);
            PvtPassengers.Add(PedHash.Business01AFY);
            PvtPassengers.Add(PedHash.Business01AMM);
            PvtPassengers.Add(PedHash.Business01AMY);
            PvtPassengers.Add(PedHash.Business02AFM);
            PvtPassengers.Add(PedHash.Business02AFY);
            PvtPassengers.Add(PedHash.Business02AMY);
            PvtPassengers.Add(PedHash.Business03AFY);
            PvtPassengers.Add(PedHash.Business03AMY);
            PvtPassengers.Add(PedHash.Business04AFY);
            AirportNames = new List<string>();
            AirportNames.Add("Desert Airlfeild");
            AirportNames.Add("Fort Zancudo outskirt");
            AirportNames.Add("MACKANZIE AIRPORT");
            AirportNames.Add("Paleto Bay Seashore");

            Airports = new List<Vector3>();
            Airports.Add(new Vector3(-92.70312f, 2740.974f, 538.8322f)); //Desert Airlfeild
            Airports.Add(new Vector3(-2768.413f, 2087.594f, 463.1091f)); // Fort Zancudo outskirt
            Airports.Add(new Vector3(1606.988f, 4477.745f, 252.1198f)); //MACKANZIE AIRPORT
            Airports.Add(new Vector3(-958.49f, 6192.991f, 196.8881f)); // Paleto Bay Seashore

            runwayStartPoints = new List<Vector3>();
            runwayStartPoints.Add(new Vector3(1044.313f, 3072.745f, 41.86372f));
            runwayStartPoints.Add(new Vector3(-2764.613f, 2699.911f, 1.303101f));
            runwayStartPoints.Add(new Vector3(1917.695f, 4705.943f, 41.22027f));
            runwayStartPoints.Add(new Vector3(-583.5499f, 6350.21f, 3.2344f));


            runwayEndPoints = new List<Vector3>();
            runwayEndPoints.Add(new Vector3(1577.859f, 3218.239f, 40.41154f));
            runwayEndPoints.Add(new Vector3(-2738.307f, 2905.755f, 1.889885f));
            runwayEndPoints.Add(new Vector3(2106.234f, 4797.56f, 41.08499f));
            runwayEndPoints.Add(new Vector3(-375.8521f, 6468.54f, 2.111773f));

            flyToAirport = Airports[0];
            runwayStartPoint = runwayStartPoints[0];
            runwayEndPoint = runwayEndPoints[0];

            nearResearvationPoint = false;
            AirplaneSpawnHeading = 326.9565f;
            driveTo = new Vector3(-1628.043f, -2727.244f, 13.46283f);
            airplaneBooked = false;
            airplaneEntered = false;
            //landingactive = false;
            seatBeltsOn = false;
            annoncementsOn = true;
            readytofly = false;
            playerNearAeroplane = false;
            flightInProgress = false;
            airplaneLanding = false;
            isHelicopter = false;
            takeOffGain = false;
            takeOffInProgress = false;
            flightSkipped = false;
            supriseActivated = false;
            RappellingOn = false;
            assistantCreated = false;
            landingGearsOFF = false;

            listPrivatePlanes = new List<VehicleHash>();
            listPrivatePlanes.Add(VehicleHash.Cuban800);
            listPrivatePlanes.Add(VehicleHash.Luxor);
            listPrivatePlanes.Add(VehicleHash.Mammatus);
            listPrivatePlanes.Add(VehicleHash.Velum);
            listPrivatePlanes.Add(VehicleHash.Velum2);
            listPrivatePlanes.Add(VehicleHash.Vestra);
            listPrivatePlanes.Add(VehicleHash.Duster);

            listAirlinesPlanes = new List<VehicleHash>();
            listAirlinesPlanes.Add(VehicleHash.Jet);
            listAirlinesPlanes.Add(VehicleHash.Miljet);
            listAirlinesPlanes.Add(VehicleHash.Shamal);

            listHelicopters = new List<VehicleHash>();
            listHelicopters.Add(VehicleHash.Buzzard2);
            listHelicopters.Add(VehicleHash.Frogger);
            listHelicopters.Add(VehicleHash.Frogger2);
            listHelicopters.Add(VehicleHash.Maverick);
            BlipreservationCentre = World.CreateBlip(reservationCenter);
            BlipreservationCentre.Color = BlipColor.Green;
            BlipreservationCentre.Sprite = BlipSprite.Airport;
            BlipreservationCentre.IsShortRange = true;

            Tick += OnTick; // Main loop event, called every few milliseconds specified via the Interval property.
            KeyUp += OnKeyUp; // Called when a key or mouse button is released.
            KeyDown += OnKeyDown; // Called when a key or mouse button is pressed.
            Interval = 0; // Tick interval in milliseconds. Set to zero to run as fast as possible.

            string path = AppDomain.CurrentDomain.BaseDirectory.ToString();
            psi = new ProcessStartInfo();
            psi.Arguments = "1";
            psi.FileName = path + "/audioplayer.exe";
            psi.WindowStyle = ProcessWindowStyle.Hidden;
            psi.CreateNoWindow = true;

        }

        void ResetValues()
        {
            flightInProgress = false;
            airplaneLanding = false;
            BlipflightStartPoint.Remove();
            
            if (assistantCreated)
            {
                Assistant.MarkAsNoLongerNeeded();
            }
            if (selectedPlaneHash == VehicleHash.Titan)
            {
                selectedAirplane.OpenDoor(VehicleDoor.Trunk, false, true);
            }
            foreach (Ped p in Passengers)
            {
                p.Task.WanderAround();
                p.MarkAsNoLongerNeeded();
            }
            isHelicopter = false;
            pilot.MarkAsNoLongerNeeded();
            selectedAirplane.MarkAsNoLongerNeeded();
            airplaneBooked = false;
            airplaneEntered = false;
            seatBeltsOn = false;
            readytofly = false;
            playerNearAeroplane = false;

            airplaneSpawned = false;
            PvtorPub = 0;
            takeOffGain = false;
            flyToAirport = Airports[0];
            runwayStartPoint = runwayStartPoints[0];
            runwayEndPoint = runwayEndPoints[0];
            customWaypoint = false;
            takeOffInProgress = false;
            assistantCreated = false;
            RappellingOn = false;
            flightSkipped = false;
            supriseActivated = false;
            flightabort = false;
            landingGearsOFF = false;
        }

        void OnTick(object sender, EventArgs e)
        {
            AirplaneTakeoffManager();
            if (World.GetDistance(reservationCenter, player.Position) < 5.0f)
            {
                UI.Notify("Press E to Book Airlines Ticket or Private Planes");
                nearResearvationPoint = true;
            }
            else
            {
                nearResearvationPoint = false;
            }
            if (_isMenuOpen)
            {
                _viewPort.Draw();
            }

            if (airplaneSpawned)
            {
                if (selectedAirplane.IsDead)
                {
                    ResetValues();
                }
            }

            if (airplaneBooked)
            {
                Game.Player.WantedLevel = 0;
            }
            // Calling native functions:
            // - No return type: GTA.Native.Function.Call(GTA.Native.Hash.SET_MAX_WANTED_LEVEL, 0);
            // - With return type: int id = GTA.Native.Function.Call<int>(GTA.Native.Hash.PLAYER_PED_ID);
        }
        void OnKeyUp(object sender, KeyEventArgs e)
        {

        }

        void OnKeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.E)
            {
                if ((!airplaneBooked && nearResearvationPoint) || airplaneEntered)
                {
                    if (!_isMenuOpen)
                    {
                        MainMenu();
                    }
                    else
                    {
                        _isMenuOpen = false;
                    }
                    return;
                }
            }
            if (_isMenuOpen)
            {
                switch (e.KeyCode)
                {
                    case Keys.NumPad5:
                        _menuItems[_selectedItem].Activate();
                        break;
                    case Keys.NumPad2:
                        if (_selectedItem + 1 <= _menuItems.Count - 1)
                        {
                            _menuItems[_selectedItem].Deselect();
                            _menuItems[++_selectedItem].Select();
                        }
                        break;
                    case Keys.NumPad8:
                        if (_selectedItem - 1 >= 0)
                        {
                            _menuItems[_selectedItem].Deselect();
                            _menuItems[--_selectedItem].Select();
                        }
                        break;
                    case Keys.NumPad0:
                        PreviousMenu();
                        break;
                }
            }

            if (e.KeyCode == Keys.Y)
            {
                if (selectedAirplane.Model != VehicleHash.CargoPlane)
                {
                    if (playerNearAeroplane && !airplaneEntered)
                    {
                        player.Task.ClearAllImmediately();
                        Wait(500);
                        player.Task.WarpIntoVehicle(selectedAirplane, VehicleSeat.Any);
                        airplaneEntered = true;
                    }
                }
                else
                {
                    airplaneEntered = true;
                }
            }
        }

        private void PreviousMenu()
        {
            switch (_branch)
            {
                case 1:
                    _isMenuOpen = false;
                    break;
                case 2:
                    MainMenu();
                    break;
            }
        }

        private void PrepareMenuPhase1()
        {
            _menuItems.Clear();
            _selectedItem = 0;
        }

        private void PrepareMenuPhase2(string caption)
        {
            GTA.Menu menu = new GTA.Menu(String.Format(" {0}", caption), _menuItems.ToArray()) { Width = 500 };
            _viewPort.MenuPosition = new Point(0, 0);
            menu.UnselectedItemColor = Color.BlanchedAlmond;
            menu.SelectedItemColor = Color.White;
            menu.HeaderHeight = 50;
            menu.HeaderTextScale = 1;
            menu.HeaderFont = GTA.Font.Monospace;
            menu.HeaderColor = Color.Black;
            menu.HeaderTextColor = Color.Red;
            menu.SelectedTextColor = Color.Red;
            menu.UnselectedTextColor = Color.OrangeRed;
            menu.FooterHeight = 0;
            _viewPort = new Viewport();
            _viewPort.AddMenu(menu);
            _branch = 2;
            _viewPort.MenuPosition = new Point(Screen.PrimaryScreen.Bounds.X + 1, Screen.PrimaryScreen.Bounds.Y + 1);
        }

        void MainMenu()
        {
            _selectedItem = 0;
            GTA.MenuButton btnPvtPlanes = new GTA.MenuButton("PRIVATE PLANES");
            GTA.MenuButton btnAirlines = new GTA.MenuButton("AIRLINES");
            GTA.MenuButton btnCargoServices = new GTA.MenuButton("Cargo Services");
            GTA.MenuButton btnHelicopters = new GTA.MenuButton("Skydiving Helicopters");
            GTA.MenuButton btnAnnouncement = new GTA.MenuButton("On/Off Announcements");

            btnAnnouncement.Activated += btnAnnouncement_Activated;
            btnPvtPlanes.Activated += btnPvtPlanes_Activated;
            btnAirlines.Activated += btnAirlines_Activated;
            btnCargoServices.Activated += btnCargoServices_Activated;
            btnHelicopters.Activated += btnHelicopters_Activated;
            if (!airplaneBooked && nearResearvationPoint)
            {
                _menuItems = new List<GTA.IMenuItem>()
            {
                btnPvtPlanes,
                btnAirlines,
                btnCargoServices,
                btnHelicopters,
                btnAnnouncement
            };
            }

            GTA.MenuButton btnAddPassengers = new GTA.MenuButton("Add Passenger");
            GTA.MenuButton btnStartFlight = new GTA.MenuButton("Start Journey");
            GTA.MenuButton btnSkipFlight = new GTA.MenuButton("Skip Journey");
            GTA.MenuButton btnSuprise = new GTA.MenuButton("Suprise");
            GTA.MenuButton btnOpenCargoDoors = new GTA.MenuButton("Open CargoPlane Doors");
            GTA.MenuButton btnRappel = new GTA.MenuButton("Rappel From Helicopter");

            btnAddPassengers.Activated += btnAddPassengers_Activated;
            btnStartFlight.Activated += btnStartFlight_Activated;
            btnSkipFlight.Activated += btnSkipFlight_Activated;
            btnSuprise.Activated += btnSuprise_Activated;
            btnOpenCargoDoors.Activated += btnOpenCargoDoors_Activated;
            btnRappel.Activated += btnRappel_Activated;

            if (airplaneEntered)
            {
                _menuItems = new List<GTA.IMenuItem>()
            {
                btnAddPassengers,
                btnStartFlight,
                btnSkipFlight,
                btnSuprise
            };

                if (selectedAirplane.Model == VehicleHash.CargoPlane)
                {
                    _menuItems.Add(btnOpenCargoDoors);
                }
                if (isHelicopter)
                {
                    _menuItems.Add(btnRappel);
                }

                if (RappellingOn)
                {
                    _menuItems.Remove(btnRappel);
                }
                if (flightSkipped)
                {
                    _menuItems.Remove(btnSkipFlight);
                }
                if (supriseActivated)
                {
                    _menuItems.Remove(btnSuprise);
                }
                if (readytofly)
                {
                    _menuItems.Remove(btnStartFlight);
                }
            }

            _branch = 1;
            GTA.Menu menu = new GTA.Menu("WELCOME TO LOS SANTOS AIRLINES", _menuItems.ToArray()) { Width = 500 };
            menu.UnselectedItemColor = Color.BlanchedAlmond;
            menu.SelectedItemColor = Color.White;
            menu.HeaderHeight = 50;
            menu.HeaderTextScale = 1;
            menu.HeaderFont = GTA.Font.Monospace;
            menu.HeaderColor = Color.Black;
            menu.HeaderTextColor = Color.Red;
            menu.SelectedTextColor = Color.Red;
            menu.UnselectedTextColor = Color.OrangeRed;
            menu.FooterHeight = 0;
            _viewPort = new Viewport();
            _viewPort.AddMenu(menu);
            _isMenuOpen = true;
            _viewPort.MenuPosition = new Point(Screen.PrimaryScreen.Bounds.X + 1, Screen.PrimaryScreen.Bounds.Y + 1);
        }

        void btnRappel_Activated(object sender, EventArgs e)
        {
            if (!RappellingOn && airplaneLanding && selectedAirplane.Model == VehicleHash.Maverick)
            {
                Function.Call(Hash.TASK_HELI_MISSION, pilot, selectedAirplane, 0, 0, selectedAirplane.Position.X, selectedAirplane.Position.Y, World.GetGroundHeight(selectedAirplane.Position) + 110.0f, 4, 50.0, -1.0, -1.0, 2, 2, 5.0, 0);
                RappellingOn = true;
                _isMenuOpen = false;
                UI.ShowSubtitle("Pilot will now take you to a suitable height from which you can rappel safetly");
                UI.Notify("Rappeling is done automatically .. Sit back and Relax");
            }
            else
            {
                UI.ShowSubtitle("You can only rappel from Maverick");
            }

        }

        void btnOpenCargoDoors_Activated(object sender, EventArgs e)
        {
            selectedAirplane.OpenDoor(VehicleDoor.Trunk, true, true);
            selectedAirplane.OpenDoor(VehicleDoor.BackLeftDoor, true, true);
            selectedAirplane.OpenDoor(VehicleDoor.Trunk2, true, true);
            selectedAirplane.OpenDoor(VehicleDoor.Hood, true, true);
        }

        void btnSuprise_Activated(object sender, EventArgs e)
        {
            if (flightInProgress && !supriseActivated)
            {
                supriseActivated = true;
                Game.FadeScreenOut(1000);
                Wait(1000);
                Game.FadeScreenIn(1000);
                Wait(500);
                Game.FadeScreenOut(500);
                Wait(1000);
                Game.FadeScreenIn(500);
                Game.FadeScreenOut(1000);
                Wait(1000);
                Game.FadeScreenIn(1000);
                Wait(500);
                Game.FadeScreenOut(500);
                Wait(1000);
                Game.FadeScreenIn(500);
                Wait(2000);
                selectedAirplane.Position = new Vector3(1000f, 1000f, 5000f);
                pilot.Kill();
                UI.ShowSubtitle("Suprise Mothaf*ker");
                _isMenuOpen = false;
            }
        }

        void btnSkipFlight_Activated(object sender, EventArgs e)
        {
            if (flightInProgress && !flightSkipped)
            {
                if (selectedAirplane.Model != VehicleHash.CargoPlane)
                {
                    Game.FadeScreenOut(2000);
                    Wait(3000);
                    selectedAirplane.Position = flyToAirport.Around(10.0f);
                    Game.FadeScreenIn(2000);
                    flightSkipped = true;
                    _isMenuOpen = false;
                }
                else
                {
                    UI.ShowSubtitle("You Cannot Skip Flight in Cargo Services / You have already skipped flight..");
                }
            }
        }
        void btnStartFlight_Activated(object sender, EventArgs e)
        {
            if (airplaneEntered && !readytofly)
            {
                player.Task.PlayAnimation("anim@mp_player_intincarthumbs_upstd@ds@", "idle_a", 8f, 5, false, 1.0f);
                readytofly = true;
            }
            _isMenuOpen = false;
        }

        void btnAddPassengers_Activated(object sender, EventArgs e)
        {
            if (Passengers.Count <= selectedAirplane.PassengerSeats - 3)
            {
                if (PvtorPub == 2)
                {

                    // Passengers.Add(World.CreateRandomPed(AirlplaneSpawnPoint.Around(10.0f)));
                    Passengers.Add(selectedAirplane.CreateRandomPedOnSeat(VehicleSeat.Any));
                    Passengers[Passengers.Count - 1].Model.MarkAsNoLongerNeeded();
                    Passengers[Passengers.Count - 1].Task.WarpIntoVehicle(selectedAirplane, VehicleSeat.Any);
                }
                if (PvtorPub == 1)
                {
                    Passengers.Add(selectedAirplane.CreatePedOnSeat(VehicleSeat.Any, PvtPassengers[r.Next(0, 10)]));
                    Passengers[Passengers.Count - 1].Model.MarkAsNoLongerNeeded();
                    Passengers[Passengers.Count - 1].Task.WarpIntoVehicle(selectedAirplane, VehicleSeat.Any);
                }
            }
        }

        void btnAnnouncement_Activated(object sender, EventArgs e)
        {
            if (annoncementsOn)
            {
                annoncementsOn = false;
                UI.ShowSubtitle("Announcments OFF");
            }
            else
            {
                if (!annoncementsOn)
                {
                    annoncementsOn = true;
                    UI.ShowSubtitle("Announcments ON");
                }
            }
        }
        void btnHelicopters_Activated(object sender, EventArgs e)
        {
            PrepareMenuPhase1();
            _menuItems = new List<GTA.IMenuItem>();
            foreach (VehicleHash v in listHelicopters)
            {
                _menuItems.Add(new GTA.MenuButton(v.ToString()));
            }

            foreach (GTA.MenuButton mb in _menuItems)
            {
                mb.Activated += Helicopter_Selected;

            }
            PrepareMenuPhase2("Airlines");
        }

        void Helicopter_Selected(object sender, EventArgs e)
        {
            selectedPlaneHash = listHelicopters[_selectedItem];
            isHelicopter = true;
            CheckpointManager();

        }
        void btnAirlines_Activated(object sender, EventArgs e)
        {
            PrepareMenuPhase1();
            _menuItems = new List<GTA.IMenuItem>();
            foreach (VehicleHash v in listAirlinesPlanes)
            {
                _menuItems.Add(new GTA.MenuButton(v.ToString()));
            }

            foreach (GTA.MenuButton mb in _menuItems)
            {
                mb.Activated += AirlinePlanes_Activated;

            }
            PrepareMenuPhase2("Airlines");
        }

        void btnPvtPlanes_Activated(object sender, EventArgs e)
        {
            PrepareMenuPhase1();
            _menuItems = new List<GTA.IMenuItem>();
            foreach (VehicleHash v in listPrivatePlanes)
            {
                _menuItems.Add(new GTA.MenuButton(v.ToString()));
            }

            foreach (GTA.MenuButton mb in _menuItems)
            {
                mb.Activated += PrivatePlanes_Activated;

            }
            PrepareMenuPhase2("Airlines");

        }

        void btnCargoServices_Activated(object sender, EventArgs e)
        {


            if (flightCounter != 0)
            {
                selectedAirplane.Delete();
                pilot.Delete();
            }

            selectedPlaneHash = VehicleHash.CargoPlane;
            //     selectedAirplane = World.CreateVehicle(listPrivatePlanes[_selectedItem], AirlplaneSpawnPoint, AirplaneSpawnHeading);
            PrepareMenuPhase1();
            _menuItems = new List<GTA.IMenuItem>();
            foreach (string s in AirportNames)
            {
                _menuItems.Add(new GTA.MenuButton(s));
            }

            foreach (GTA.MenuButton mb in _menuItems)
            {
                mb.Activated += Airport_Selected;

            }
            GTA.MenuButton btnCheckpoint = new MenuButton("Fly to custom Location");
            btnCheckpoint.Activated += btnCheckpoint_Activated;
            _menuItems.Add(btnCheckpoint);
            PrepareMenuPhase2("Select Airport");
        }

        void PrivatePlanes_Activated(object sender, EventArgs e)
        {
            if (flightCounter != 0)
            {
                selectedAirplane.Delete();
                pilot.Delete();

            }
            selectedPlaneHash = listPrivatePlanes[_selectedItem];
            PrepareMenuPhase1();
            _menuItems = new List<GTA.IMenuItem>();
            foreach (string s in AirportNames)
            {
                _menuItems.Add(new GTA.MenuButton(s));
            }

            foreach (GTA.MenuButton mb in _menuItems)
            {
                mb.Activated += Airport_Selected;

            }
            GTA.MenuButton btnCheckpoint = new MenuButton("Fly to custom Location");
            btnCheckpoint.Activated += btnCheckpoint_Activated;
            _menuItems.Add(btnCheckpoint);
            PrepareMenuPhase2("Select Airport");



        }

        void btnCheckpoint_Activated(object sender, EventArgs e)
        {
            CheckpointManager();
        }

        void CheckpointManager()
        {
            List<Blip> activeBlips = new List<Blip>();
            Checkpoint = null;
            foreach (Blip b in World.GetActiveBlips())
            {
                if (b.Type == 4)
                {
                    customWaypoint = true;
                    Checkpoint = b;
                    flyToAirport.X = b.Position.X;
                    flyToAirport.Y = b.Position.Y;
                    flyToAirport.Z = 1000f;
                    runwayStartPoint = runwayStartPoints[0];
                    runwayEndPoint = runwayEndPoints[0];
                    Game.Player.Money -= 15000;
                    airplaneBooked = true;
                    _isMenuOpen = false;
                    Function.Call(Hash.CLEAR_AREA_OF_VEHICLES, AirlplaneSpawnPoint.X, AirlplaneSpawnPoint.Y, AirlplaneSpawnPoint.Z, 200.0f, 1, 1, 1, 1, 1);
                    Function.Call(Hash.CLEAR_AREA_OF_OBJECTS, AirlplaneSpawnPoint.X, AirlplaneSpawnPoint.Y, AirlplaneSpawnPoint.Z, 200.0f);
                    ClearRunway();
                }
            }

            if (!customWaypoint)
            {
                UI.ShowSubtitle("Please Set A CheckPoint First");
            }
        }
        void Airport_Selected(object sender, EventArgs e)
        {
            flyToAirport = Airports[_selectedItem];
            runwayStartPoint = runwayStartPoints[_selectedItem];
            runwayEndPoint = runwayEndPoints[_selectedItem];
            customWaypoint = false;
            Function.Call(Hash.CLEAR_AREA_OF_VEHICLES, AirlplaneSpawnPoint.X, AirlplaneSpawnPoint.Y, AirlplaneSpawnPoint.Z, 200.0f, 1, 1, 1, 1, 1);
            Function.Call(Hash.CLEAR_AREA_OF_OBJECTS, AirlplaneSpawnPoint.X, AirlplaneSpawnPoint.Y, AirlplaneSpawnPoint.Z, 200.0f);
            UI.Notify(AirportNames[_selectedItem]);
            Game.Player.Money -= 5000;
            airplaneBooked = true;
            _isMenuOpen = false;
            PvtorPub = 1;
            ClearRunway();
        }
        void AirlinePlanes_Activated(object sender, EventArgs e)
        {
            //if (flightCounter != 0)
            //{
            //    selectedAirplane.Delete();
            //    pilot.Delete();
            //}
            selectedPlaneHash = (listAirlinesPlanes[_selectedItem]);
            Game.Player.Money -= 500;
            customWaypoint = false;
            airplaneBooked = true;
            _isMenuOpen = false;
            PvtorPub = 2;
            ClearRunway();
        }

        void ClearRunway()
        {
            Function.Call(Hash.CLEAR_AREA_OF_VEHICLES, AirlplaneSpawnPoint.X, AirlplaneSpawnPoint.Y, AirlplaneSpawnPoint.Z, 200.0f, true, true, true, true, true);
            Wait(50);
            Function.Call(Hash.CLEAR_AREA_OF_OBJECTS, AirlplaneSpawnPoint.X, AirlplaneSpawnPoint.Y, AirlplaneSpawnPoint.Z, 200.0f, true);
            Wait(50);
            Function.Call(Hash.CLEAR_AREA, AirlplaneSpawnPoint.X, AirlplaneSpawnPoint.Y, AirlplaneSpawnPoint.Z, 200.0f, true, true, true, true);
            Wait(50);
            Function.Call(Hash.CLEAR_AREA_OF_PROJECTILES, AirlplaneSpawnPoint.X, AirlplaneSpawnPoint.Y, AirlplaneSpawnPoint.Z, 200.0f, true);
            Wait(50);
            Function.Call(Hash.CLEAR_AREA_OF_PEDS, AirlplaneSpawnPoint.X, AirlplaneSpawnPoint.Y, AirlplaneSpawnPoint.Z, 200.0f, true);
            Vehicle temp = World.GetClosestVehicle(AirlplaneSpawnPoint, 50f);
            if (temp != null)
            {
                temp.Delete();
            }
            AirplaneSpawwner();
        }

        void AirplaneSpawwner()
        {
            Game.FadeScreenOut(2000);
            Wait(1000);
            selectedAirplane = World.CreateVehicle(selectedPlaneHash, AirlplaneSpawnPoint, AirplaneSpawnHeading);
            pilot = selectedAirplane.CreatePedOnSeat(VehicleSeat.Driver, PedHash.Pilot01SMY);
            Wait(1000);
            pilot.BlockPermanentEvents = true;
            Wait(500);
            if (selectedPlaneHash == VehicleHash.CargoPlane)
            {
                selectedAirplane.OpenDoor(VehicleDoor.Trunk, false, true);
                selectedAirplane.OpenDoor(VehicleDoor.BackLeftDoor, false, true);
                selectedAirplane.OpenDoor(VehicleDoor.Trunk2, false, true);
                selectedAirplane.OpenDoor(VehicleDoor.Hood, false, true);
                Function.Call(Hash.SET_VEHICLE_DOOR_OPEN, selectedAirplane, 6, false, true);
                Function.Call(Hash.SET_VEHICLE_DOOR_OPEN, selectedAirplane, 7, false, true);
            }
            if (selectedAirplane.PassengerSeats > 1)
            {
                Assistant = selectedAirplane.CreatePedOnSeat(VehicleSeat.Passenger, PedHash.Pilot02SMM);
            }
            player.Position = AirlplaneSpawnPoint.Around(50.0f);
            pilot.RelationshipGroup = player.RelationshipGroup;
            selectedAirplane.PlaceOnGround();
            if (selectedAirplane.Model.IsHelicopter)
            {
                selectedAirplane.Position = World.GetNextPositionOnStreet(AirlplaneSpawnPoint);
            }
            playerCar = player.CurrentVehicle;
            BlipflightStartPoint = selectedAirplane.AddBlip();
            BlipflightStartPoint.Color = BlipColor.Blue;
            BlipflightStartPoint.Sprite = BlipSprite.Airport;
            Wait(1000);
            Game.FadeScreenIn(2000);
            airplaneSpawned = true;
            selectedAirplane.Model.MarkAsNoLongerNeeded();
            pilot.Model.MarkAsNoLongerNeeded();
        }

        void AirplaneTakeoffManager()
        {
            if (!flightabort)
            {
                if (!airplaneEntered && airplaneSpawned)
                {
                    if (World.GetDistance(selectedAirplane.Position, player.Position) < 10.0f)
                    {
                        UI.ShowSubtitle("Press Y to Board the Plane");
                        playerNearAeroplane = true;
                    }
                    else
                    {
                        playerNearAeroplane = false;
                    }
                }

                if (airplaneEntered && !readytofly)
                {
                    UI.ShowSubtitle("Press E to get Inflight Menu");
                }

                if (airplaneEntered && readytofly && !flightInProgress)
                {

                    if (!isHelicopter && selectedAirplane.PassengerSeats > 4)
                    {
                        if (annoncementsOn)
                        {
                            Process proc = Process.Start(psi);
                        }
                    }

                    if (selectedPlaneHash == VehicleHash.CargoPlane)
                    {
                        selectedAirplane.CloseDoor(VehicleDoor.Trunk, true);
                        selectedAirplane.CloseDoor(VehicleDoor.BackLeftDoor, true);
                        selectedAirplane.CloseDoor(VehicleDoor.BackLeftDoor, true);
                        selectedAirplane.CloseDoor(VehicleDoor.Trunk2, true);
                        selectedAirplane.CloseDoor(VehicleDoor.Hood, true);
                    }
                    if (!isHelicopter)
                    {
                        Function.Call(Hash.TASK_PLANE_MISSION, pilot, selectedAirplane, 0, 0, flyToAirport.X, flyToAirport.Y, flyToAirport.Z, 4, 30f, 50f, -1f, 100, 20);
                    }
                    else
                    {
                        Function.Call(Hash.TASK_HELI_MISSION, pilot, selectedAirplane, 0, 0, flyToAirport.X, flyToAirport.Y, flyToAirport.Z, 4, 50.0, -1.0, -1.0, 2, 2, 5.0, 0);
                    }
                    flightInProgress = true;
                    Wait(5000);
                    Function.Call(Hash.SET_PLAYER_CAN_DO_DRIVE_BY, player, true);

                }
                if (flightInProgress)
                {
                    if (selectedAirplane.HeightAboveGround > 20 && !airplaneLanding)
                    {
                        Function.Call(Hash._0xCFC8BE9A5E1FE575, selectedAirplane, 1);
                        //Wait(500);
                    }

                    if (selectedAirplane.Model != VehicleHash.CargoPlane && !isHelicopter)
                    {
                        if (!player.IsInVehicle(selectedAirplane))
                        {
                            flightabort = true;
                            UI.ShowSubtitle("Flight Aborted");
                            ResetValues();
                        }
                    }
                    else
                    {
                        if (World.GetDistance(selectedAirplane.Position, player.Position) > 300.0f)
                        {
                            flightabort = true;
                            UI.ShowSubtitle("Flight Aborted");
                            ResetValues();
                        }
                    }
                   
                    if (!airplaneLanding)
                    {
                        if (World.GetDistance(selectedAirplane.Position, flyToAirport) < 100.0f)
                        {
                            airplaneLanding = true;
                            if (!isHelicopter)
                            {
                                Function.Call(Hash.TASK_PLANE_MISSION, pilot, selectedAirplane, 0, 0, flyToAirport.X, flyToAirport.Y, flyToAirport.Z, 4, 30f, 50f, -1f, 50, 0);
                                Wait(500);
                                Function.Call(Hash.TASK_PLANE_LAND, pilot, selectedAirplane, runwayStartPoint.X, runwayStartPoint.Y, runwayStartPoint.Z, runwayEndPoint.X, runwayEndPoint.Y, runwayEndPoint.Z);
                                if (selectedAirplane.Model == VehicleHash.CargoPlane)
                                {
                                    Wait(4000);
                                    pilot.Task.CruiseWithVehicle(selectedAirplane, 1f);
                                }
                            }
                            else
                            {
                                Wait(4000);
                                pilot.Task.CruiseWithVehicle(selectedAirplane, 1f);
                            }
                           
                            if (customWaypoint)
                            {
                                UI.ShowSubtitle("We have reached the skydiving point !, You can jump off");

                            }
                            else
                            {
                                if (!isHelicopter)
                                {
                                    if (selectedAirplane.Model != VehicleHash.CargoPlane)
                                    {
                                        UI.ShowSubtitle("We Are going to land now !");
                                        psi.Arguments = "2";
                                        if (selectedAirplane.PassengerSeats > 4)
                                        {
                                            if (annoncementsOn)
                                            {
                                                Process proc = Process.Start(psi);
                                            }
                                        }
                                    }
                                }
                            }

                        }
                    }

                }

                if (airplaneLanding)
                {
                    if(World.GetDistance(selectedAirplane.Position,runwayEndPoint) < 1.0f)
                    {
                        
                    }
                    if (selectedAirplane.Speed <= 2)
                    {

                        psi.Arguments = "3";
                        if (!isHelicopter && selectedAirplane.PassengerSeats > 4)
                        {
                            if (annoncementsOn)
                            {
                                Process proc = Process.Start(psi);
                            }
                        }
                        if (!isHelicopter)
                        {
                            flightabort = true;
                            ResetValues();
                            UI.ShowSubtitle("Flight Successful");
                        }

                        if (isHelicopter || selectedAirplane.Model == VehicleHash.CargoPlane)
                        {
                            if (RappellingOn)
                            {
                                if (player.HeightAboveGround <= 1)
                                {
                                    flightabort = true;
                                    Wait(5000);
                                    ResetValues();
                                    UI.ShowSubtitle("Flight Successful");
                                }

                                if (selectedAirplane.HeightAboveGround <= 120 && selectedAirplane.Speed <= 1)
                                {
                                    Function.Call((Hash)678138103285225033, player, 0);
                                }
                            }
                            else
                            {
                                if (!player.IsInVehicle(selectedAirplane))
                                {
                                    flightabort = true;
                                    ResetValues();
                                    UI.ShowSubtitle("Flight Successful");
                                }
                            }
                        }

                    }
                }
            }
        }

        protected override void Dispose(bool A_0)
        {
            if (BlipreservationCentre.Exists())
            {
                BlipreservationCentre.Remove();
            }
            if (BlipreservationCentre.Exists())
            {
                BlipflightStartPoint.Remove();
            }
            base.Dispose(A_0);
        }
    }
}

